/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年4月6日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.gateway.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

/**
 * @FileName RequestUtil1.java
 * @Description: Request工具类
 *
 * @Date 2017年4月6日 下午2:20:51
 * @author li.shangzhi
 * @version 1.0
 */
public class RequestUtil {

	/**
	 * @Title: getUrl
	 * @Description: 获取完整的URL
	 * @param request
	 * @return
	 * @author li.shangzhi
	 * @date 2017年4月6日 下午2:21:42
	 */
	public static String getUrl(HttpServletRequest request) {
		StringBuilder urlBuilder = new StringBuilder();
		try {
			urlBuilder.append(getRootPath(request, false));
			// 格式化中文字符，防止出现乱码
			if (StringUtils.isNotBlank(request.getQueryString())) {
				String query = "?" + new String(request.getQueryString().trim().getBytes("ISO-8859-1"));
				urlBuilder.append(query);
			}
			return URLEncoder.encode(urlBuilder.toString(), "UTF-8");
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * @Title: getRootPath
	 * @Description: 获得根路径
	 * @param request
	 * @param includePort
	 * @return
	 * @author li.shangzhi
	 * @date 2017年4月6日 下午2:22:12
	 */
	public static String getRootPath(HttpServletRequest request, boolean includePort) {
		StringBuilder urlBuilder = new StringBuilder();
		urlBuilder.append(request.getScheme());
		urlBuilder.append("://");
		String host = request.getHeader("Host");
		if (StringUtils.isBlank(host)) {
			host = request.getServerName();
		}
		urlBuilder.append(host);
		if (includePort) {
			urlBuilder.append(":");
			urlBuilder.append(request.getServerPort());
		}
		String context = request.getContextPath();
		if (StringUtils.isBlank(context)) {
			context = getOriginalUri(request);
		}
		urlBuilder.append(context);
		return urlBuilder.toString();
	}

	/**
	 * @Title: getOriginalUri
	 * @Description: 利用urlrewrite.jar加入的属性获得原始URI
	 * @param request
	 * @return
	 * @author li.shangzhi
	 * @date 2017年4月6日 下午2:22:31
	 */
	public static String getOriginalUri(HttpServletRequest request) {
		return request.getAttribute("javax.servlet.forward.request_uri").toString();
	}

	/**
	 * @Title: setCookie
	 * @Description: 设置COOKIES
	 * @param response
	 * @param key
	 *            字段名
	 * @param value
	 *            字段值
	 * @param day
	 *            保持天数
	 * @author li.shangzhi
	 * @date 2017年4月6日 下午2:22:51
	 */
	public static void setCookie(HttpServletResponse response, String key, String value, int day) {
		if (StringUtils.isNotBlank(value)) {
			Cookie res = new Cookie(key, value);
			// res.setPath(COOKIES_BASE);设置路径
			res.setMaxAge((day == 0 ? day : getCookieExpires(day)));
			response.addCookie(res);
		}
	}

	public static void removeCookie(HttpServletResponse response, String key) {
		setCookie(response, key, null, 0);
	}

	public static int getCookieExpires(int day) {
		Calendar ca = Calendar.getInstance();
		ca.add(Calendar.DATE, day);
		return (int) ((ca.getTime().getTime() - new Date().getTime()) / 1000);
	}

	public static String getCookies(HttpServletRequest request, String key) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (key.equals(cookie.getName())) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * @Title: getIpAddr
	 * @Description: 获得IP地址
	 * @param request
	 * @return
	 * @author li.shangzhi
	 * @date 2017年4月6日 下午2:23:19
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return StringUtils.isNotBlank(ip) ? ip.split(",")[0] : null;
	}

	/**
	 * @Title: getBrowingType
	 * @Description: 判断浏览器类型
	 * @param request
	 * @return
	 * @author li.shangzhi
	 * @date 2017年4月6日 下午2:23:32
	 */
	public static Integer getBrowingType(HttpServletRequest request) {
		String agent = request.getHeader("USER-AGENT");
		if (null != agent && -1 != agent.indexOf("MSIE")) {
			return 1;
		} else if (null != agent && -1 != agent.indexOf("Firefox")) {
			return 2;
		} else if (null != agent && -1 != agent.indexOf("Safari")) {
			return 3;
		} else {
			return 4;
		}
	}

	/**
	 * @Title: getDomain
	 * @Description: 获取来源头信息，获取域名
	 * @param request
	 * @return
	 * @author li.shangzhi
	 * @date 2017年4月6日 下午2:23:42
	 */
	public static String getDomain(HttpServletRequest request) {
		String domain = null;

		String domainreferer = request.getHeader("referer");
		if (domainreferer != null) {
			String replaceReferer = domainreferer.replace("http://", "");
			if (domainreferer != null && replaceReferer.indexOf("/") > 0) {
				domain = replaceReferer.substring(0, replaceReferer.indexOf("/"));// 获取原URL域名
			} else {
				domain = replaceReferer.substring(0, replaceReferer.length());
			}

		}
		return domain;
	}

	/**
	 * @Title: getServiceName
	 * @Description: 获取服务器路径
	 * @param request
	 * @return
	 * @author li.shangzhi
	 * @date 2017年4月6日 下午2:23:52
	 */
	public static String getServiceName(HttpServletRequest request) {
		String path = request.getContextPath();
		String servicePath = request.getServerName() + ":" + String.valueOf(request.getServerPort());
		return "http://" + servicePath + path + "/";
	}

	public static String urlEncode(String url) {
		try {
			return URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
}
